<?php
require_once '../entry.php';
require_once 'common.php';

//$url = 'http://www.yyets.com/resource/10996';
//$url = 'http://www.yyets.com/resource/28946';

function saveOneItem( $url, $detailInfo ){
    error_log("begin process $url\n", 3, "fetch_detail.log");

    $html = file_get_contents($url);

    if( empty( $detailInfo['imgUrl'] ) ){
        list( $junk, $tail ) = split('<div class="f_l_img">', $html);
        list( $imgContent, $junk ) = split('添加到我的收藏', $html);
        
        $detailInfo['imgUrl'] = GetInnerString( $imgContent, "<img src=\"", "\"");
    }
    
    list( $junk, $tail ) = split('<div class=\"f_r_info\">', $html);
    list( $content, $junk ) = split('查看全部资讯&gt;', $tail);

    list( $intro, $downloads, $images, $comments, $infos ) = explode('<div class="box_4">', $content);

    $finalResult = array();

    // 概览
    error_log("processing intro...\n", 3, "fetch_detail.log");
    $detailStr = GetInnerString($intro, "<ul class=\"r_d_info\">", "</ul>");
    $details = explode("<li>", $detailStr);
    $introResult = array();
    foreach ($details as $detail) {
        if (strpos($detail, '<font class="f5">') !== false) {
            list($first, $second ) = explode('<font class="f5">', $detail);
            processIntro($first, $introResult);
            processIntro($second, $introResult);
        } else {
            processIntro($detail, $introResult);
        }
    }
    $finalResult['intro'] = $introResult;
    
    // remove content before 展开全文
    $pos = strpos($finalResult['intro']['简介'], '[展开全文]');
    if ($pos !== false) {
        $finalResult['intro']['简介'] = substr($finalResult['intro']['简介'], strpos($finalResult['intro']['简介'], '[展开全文]') + 14);
    }
    
    // 处理重要信息
    $finalResult['important'] = array();
    foreach ($finalResult['intro'] as $key => $value) {
        switch ($key) {
            case "地区":
                $finalResult['important']['location'] = $value;
                break;
            case "英文":
                $finalResult['important']['englishname'] = $value;
                break;
            case "别名":
                $finalResult['important']['othername'] = $value;
                break;
            case "主演":
                $finalResult['important']['actors'] = $value;
                break;
            case "语言":
                $finalResult['important']['language'] = $value;
                break;
            case "制作公司":
                $finalResult['important']['company'] = $value;
                break;
            case "类型":
                $finalResult['important']['type'] = $value;
                break;
            case "播出":
                $finalResult['important']['channel'] = $value;
                break;
            case "首播日期":
                $finalResult['important']['pubtime'] = $value;
                break;
            case "上映日期":
                $finalResult['important']['showtime'] = $value;
                break;
            case "年代":
                $finalResult['important']['year'] = $value;
                break;
            case "编剧":
                $finalResult['important']['story'] = $value;
                break;
            case "导演":
                $finalResult['important']['director'] = $value;
                break;
        }
    }

    // 下载链接处理
    error_log("processing download...\n", 3, "fetch_detail.log");
    $seasons = explodeIgnoreFirst('<ul class="resod_list"', $downloads);
    $download = array();
    foreach( $seasons as $season ){
        $seasonArr = array();
        $seasonNum = GetInnerString( $season, "season=\"", "\"");

        $episodes = explodeIgnoreFirst( "<li ", $season);
        // 处理每个资源
        $downloadItem = array();
        foreach($episodes as $episode){
            list($basic, $links) = explode( '<span class="r lks-2">', $episode);
            $downloadItem['type'] = GetInnerString( $basic, "format=\"", "\"");
            $downloadItem['size'] = GetInnerString( $basic, "<font class=\"f5\">", "</font>");
            $downloadItem['title'] = strip_tags( GetInnerString( $basic, "<span class=\"a\">", "</span>") );

            $downloadItem['edk'] = GetInnerString( $links, "<a type=\"ed2k\" href=\"", "\"");
            
            $magnet = GetInnerString( $links, "<a href=\"", "\" type=\"magnet\"");
            if(strpos($magnet, "magnet:") !== false ){
                $downloadItem['magnet'] = $magnet;
            }
            else{
                $downloadItem['magnet'] = "";
            }

            $seasonArr[] = $downloadItem;
        }

        $download[$seasonNum] = $seasonArr;
    }
    $finalResult['download'] = $download;

    // 处理图片
    error_log("processing image...\n", 3, "fetch_detail.log");
    $images = explodeIgnoreFirst( "<li>", $images);
    $imageArr = array();
    foreach( $images as $image ){
        $imageUrl = GetInnerString( $image, "<img src=\"", "\"");
        $imageArr[] = $imageUrl;
    }
    $finalResult['image'] = $imageArr;

    // 忽略剧评
    //error_log("processing comments...\n", 3, "fetch_detail.log");
    //echo $comments;

    // 处理资讯
    error_log("processing info...\n", 3, "fetch_detail.log");
    $infos = explodeIgnoreFirst( "<li", $infos);
    $infoArr = array();
    foreach( $infos as $info ){
        $infoItem = array();
        $infoItem['url'] = GetInnerString( $info, "<a href=\"", "\"");
        $infoItem['title'] = GetInnerString( $info, "target=\"_blank\">", "</a>");
        $infoArr[] = $infoItem;
    }
    $finalResult['info'] = $infoArr;
    $finalResult = array_merge( $detailInfo, $finalResult );
    
    // all finished
    error_log("process $url finished\n", 3, "fetch_detail.log");
    error_log("\n\n\n", 3, "fetch_detail.log");

    $content = var_export($finalResult, true);
    $content = "<?php \nreturn ".$content.";";

    $fileName = basename($url).".php";
    $filePath = CRAWLER_DATA.floor( $fileName/100 )."/";
    if(!is_dir($filePath)){
        mkdir($filePath , 0777, true );
    }
    file_put_contents( $filePath.$fileName, $content );
    
    // save to current crawlered file
    file_put_contents( CRAWLER_DELTA_FILE, basename($url)."\n", FILE_APPEND );
}



/**
 * process intro item
 * @param type $detail
 * @param type $introResult 
 */
function processIntro($detail, &$introResult) {
    $detail = strip_tags($detail);
    $detail = str_replace("&nbsp;", "", $detail);
    list($key, $value) = split("：", $detail, 2);
    
    $key = trim($key);
    $value = trim($value);
    if( !empty($key)){
        $introResult[$key] = $value;
    }
}

/**
 * explode，忽略第一個返回內容
 * 
 * @param type $delimiter
 * @param type $string
 * @return type 
 */
function explodeIgnoreFirst( $delimiter, $string ){
    $arr = explode($delimiter, $string);
    array_shift( $arr );
    
    return $arr;
}
?>
